package display
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	import globals.$athena;
	
	import slices.FadeDisplayObject;
	import slices.FadeInDisplayObject;
	import slices.FadeOutDisplayObject;
	import slices.InvokeFunction;
	import slices.TimeSlice;
	
	public class ImageSlot extends Sprite
	{
//		public var prev:DisplayObject;
//		public var fadeOut:TimeSlice;
		public var fadeIn:TimeSlice;
//		public var fadingIn:Array = new Array();
		
		public function ImageSlot()
		{
			super();
		}
		
		public function setContent(v:DisplayObject):void {
			removeChildren();
//			prev = null;
			addChild(v);
		}
		
		public function changeTo(v:DisplayObject, fadeInSpeed:Number=2, fadeOutSpeed:Number=2):TimeSlice {
			clear();			
			v.alpha = 0;
			layout(v);
			addChild(v);
			fadeIn = new FadeInDisplayObject(v, fadeInSpeed);
			$athena.addTimeSlice(fadeIn);
			fadeIn.appendNext(new InvokeFunction(onFadeIn));
			return fadeIn;
		}
		
		public function layout(v:DisplayObject):void {
			var rect:Rectangle = v.getBounds(v);			
			v.x = -v.width/2 - rect.x;
			v.y = -v.height/2 - rect.y;
		}
		
		public function clear():void {
			if (fadeIn != null) {
				$athena.removeTimeSlice(fadeIn);
			}
			if (numChildren > 0) {
				var old:DisplayObject = getChildAt(numChildren-1);				
				var fadeOut:TimeSlice = new FadeOutDisplayObject(old, 2);
				fadeOut.appendNext(new InvokeFunction(onFadeOut, [fadeOut]));
				$athena.addTimeSlice(fadeOut);
			}			
		}
		
		private function onFadeOut(fade:FadeDisplayObject):void {
			if (contains(fade.target)) {
				removeChild(fade.target);
			}
		}
		
		private function onFadeIn():void {
			fadeIn = null;
		}
				
	}
}